<!--
	o   Will allow a buyer or seller to send a message
	o   Users can only send messages to buyers who already replied to them or through the properties view page
	o   Sellers can only reply to buyers who contacted them initially
-->

<h1>Create Appointment Page</h1>
<?php
if(isset($_POST['save']))
{
	if (empty($_POST['TO']))
	{
		echo "Error, please enter a recipient.\nMessage was not sent.";
		preparepage('', $_POST['DATE']);
	}
	elseif (!chkdate())
	{
		echo "Error, please enter a vaid Date (YYYY,MM,DD).\nMessage was not sent.";
		preparepage($_POST['TO'], '');
	}
	else
	{
		include('connect.php');
		$TO = $_POST['TO'];
		$query = "SELECT USRID FROM  `USERS` WHERE USERNAME='$TO'";
		$result = mysql_query($query);
		if (mysql_num_rows($result)<=0)
		{
			echo "Error, user '$TO' does not exist.";
			preparepage('', $_POST['DATE']);
		}
		else 
		{
			$TOID = mysql_result($result,0);
			$DATE = $_POST['DATE'];
			$USRID = $_SESSION['USRID'];
			$query = "INSERT INTO APPOINTMENTS(APPOINT_DATE, USRID_REQUEST, USRID_ACCEPT) 
							VALUES('$DATE', $USRID, $TOID )";
			$result = mysql_query($query);
			if (!$result) die ("Database access failed: " . mysql_error(). "<br />With " . $query);
			else echo "Message sent successfully.";
		}
		include('disconnect.php');
	}

}
else
{
	$TO = "";
	if(isset($_GET['to']))
	{
		include('connect.php');
		$query = "SELECT USERNAME FROM  `USERS` WHERE USRID=" . $_GET['to'];
		$result = mysql_query($query);
		if (mysql_num_rows($result)>0) $TO = mysql_result($result,0);
		include('disconnect.php');
	}

	$DATE = isset($_GET['date'])? $_GET['date']:"";
	preparepage($TO, $DATE);
}

function preparepage($TO, $DATE)
{
	echo <<<_END
	<form action="?page=new_appointment" method="post">
	<table width=400>
	<tr><th>TO</th><th><input type="text" name='TO' value="$TO"/></th></tr>
	<tr><th>DATE(YYYY-MM-DD)</th><th><input type="text" name='DATE' value="$DATE"/></th></tr>
	</table>
	<input type="hidden" name="save" value="yes"/>
	<input type="submit" value="Send"/>
	</form>

_END;
}

function chkdate()
{
	return isset($_POST['DATE']) && strtotime($_POST['DATE'])!=-1;
}
?>

